import 'dart:async';

import 'package:cave_flutter/config/whl_base_controller.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/whl_login/login_for_password/login_for_password_logic.dart';
import 'package:cave_flutter/pages/whl_login/view/whl_login_agreement_dialog.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../../routes/whl_app_pages.dart';

class LoginForPhoneLogic extends WhlBaseController {
  TextEditingController phoneController = TextEditingController();
  bool agreePrivateStatus = false;
  Timer? timer;
  int countDown = 60;

  doClickSendPhoneCode() {
    if (countDown != 60) return;
    if (phoneController.text.isEmpty) {
      MyToast.show('请输入手机号');
      return;
    }
    if (phoneController.text.length != 11) {
      MyToast.show('请输入正确的手机号');
      return;
    }
    if (!agreePrivateStatus) {
      Get.dialog(WhlLoginAgreementDialog(onTagAgree: () {
        agreePrivateStatus = true;
        update();
        onSendPhoneCode();
      }));
    } else {
      onSendPhoneCode();
    }
  }

  onSendPhoneCode() async {
    if (timer != null) {
      timer!.cancel();
    }
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      countDown--;
      if (countDown == 0) {
        timer.cancel();
        countDown = 60;
      }
      update();
    });
    Map<String, dynamic> params = {
      // "message": "Ut est",
      "phone": [phoneController.text],
      "type": "AUTH_CODE"
    };
    ResponseData responseData = await WhlApi.getAuthCode.post(params);
    if (responseData.isSuccess()){
      Get.toNamed(Routes.surePhoneCode, arguments: {"phone":phoneController.text});
    }
  }

  doClickLoginForPassword() {
    if (Get.isRegistered<LoginForPasswordLogic>()) {
      Get.until((route) => route.settings.name == Routes.loginForPassword);
    } else {
      Get.offNamed(Routes.loginForPassword);
    }
  }

  doClickSelect() {
    agreePrivateStatus = !agreePrivateStatus;
    update();
  }
}
